import { Model, Effect } from 'dva';
import { Reducer } from 'redux';
import { list, add, remove } from '@/services/productAttributeCategory';

export interface ProductAttributeCategory {
  id: number;
  name: string;
  attributeCount: number;
  paramCount: number;
}

export interface ProductAttributeCategoryModelState {
  categories: ProductAttributeCategory[];
}

export interface ProductAttributeCategoryModelType extends Model {
  namespace: 'productAttributeCategory';
  state: ProductAttributeCategoryModelState;
  effects: {
    query: Effect;
    add: Effect;
    remove: Effect;
  };
  reducers: {
    refresh: Reducer<ProductAttributeCategoryModelState>;
  };
}

const ProductAttributeCategoryModel: ProductAttributeCategoryModelType = {
  namespace: 'productAttributeCategory',
  state: {
    categories: [],
  },

  reducers: {
    refresh(state = { categories: [] }, action) {
      return {
        ...state,
        categories: action.categories,
      };
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      const response = yield call(list);
      yield put({
        type: 'refresh',
        categories: response,
      });
    },
    *add({ payload, callback }, { call, put }) {
      yield call(add, payload);
      yield put({
        type: 'query',
      });
      callback();
    },
    *remove({ payload }, { call, put }) {
      yield call(remove, payload);
      yield put({
        type: 'query',
      });
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname.startsWith('/product')) {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default ProductAttributeCategoryModel;
